import { createVNode as _createVNode } from "vue";
import { ref, watch, reactive, nextTick, defineComponent } from "vue";
import { numericProp, getScrollTop, preventDefault, createNamespace, makeNumericProp } from "../utils/index.mjs";
import { useEventListener, useScrollParent } from "@vant/use";
import { useTouch } from "../composables/use-touch.mjs";
import { Loading } from "../loading/index.mjs";
const [name, bem, t] = createNamespace("pull-refresh");
const DEFAULT_HEAD_HEIGHT = 50;
const TEXT_STATUS = ["pulling", "loosing", "success"];
const pullRefreshProps = {
  disabled: Boolean,
  modelValue: Boolean, // 是否处于加载状态
  headHeight: makeNumericProp(DEFAULT_HEAD_HEIGHT), // 顶部内容高度
  successText: String, // 刷新成功提示文案
  pullingText: String, // 下拉过程提示文案
  loosingText: String, // 释放过程提示文案
  loadingText: String, // 加载过程提示文案
  pullDistance: numericProp,
  successDuration: makeNumericProp(500), // 刷新成功提示展示时长(ms)
  animationDuration: makeNumericProp(300) // 动画时长
};
var stdin_default = defineComponent({
  name,
  props: pullRefreshProps,
  emits: ["change", "refresh", "update:modelValue"],
  setup(props, {
    emit,
    slots
  }) {
    let reachTop;
    const root = ref();
    const track = ref();
    // 获取上级可以滚动的父节点  无时为window
    const scrollParent = useScrollParent(root);

    // default(自定义内容)
    // normal 非下拉状态的顶部内容
    // pulling 下拉过程中顶部内容
    // loosing 释放过程中顶部内容
    // loading 加载过程中顶部内容
    // success 成功过程中顶部内容
    const state = reactive({
      status: "normal",
      distance: 0, // 跟手动画距离
      duration: 0 // 动画时间间隔
    });
    const touch = useTouch();
    // 顶部提示高度样式计算
    const getHeadStyle = () => {
      if (props.headHeight !== DEFAULT_HEAD_HEIGHT) {
        return {
          height: `${props.headHeight}px`
        };
      }
    };

    // 是否允许滑动 laoding success disabled 时禁止滑动
    const isTouchable = () => state.status !== "loading" && state.status !== "success" && !props.disabled;

    // 根据实际touch距离  计算跟手动画 移动的距离 添加阻尼感
    const ease = (distance) => {
      const pullDistance = +(props.pullDistance || props.headHeight);
      if (distance > pullDistance) {
        if (distance < pullDistance * 2) {
          // pullDistance < distance < pullDistance *2时, 跟手距离减半
          distance = pullDistance + (distance - pullDistance) / 2;
        } else {
          // distance > pullDistance*2时, 跟手距离再减半
          distance = pullDistance * 1.5 + (distance - pullDistance * 2) / 4;
        }
      }
      return Math.round(distance);
    };

     // 根据下拉距离  修改提示文本状态
     // 1.success >>> normal
     // 2.跟手动画
     // 3.pulling >>> normal
     // 4.loosing >>> loading >>> 外部状态修改 >>> success >>> normal
     // 5.外部设定Loading = true
     // 6.外部设定loading = false 
    const setStatus = (distance, isLoading) => {
      const pullDistance = +(props.pullDistance || props.headHeight);
      state.distance = distance;
      // isLoading 为true时, 忽略其它的状态
      if (isLoading) {
        state.status = "loading";
      } else if (distance === 0) {
        state.status = "normal";
      } else if (distance < pullDistance) {
        state.status = "pulling";
      } else {
        state.status = "loosing";
      }
      emit("change", {
        status: state.status,
        distance
      });
    };

    // 获取各个状态对应的提示文本  及对应国际化
    const getStatusText = () => {
      const {
        status
      } = state;
      if (status === "normal") {
        return "";
      }
      return props[`${status}Text`] || t(status);
    };

    // 各种状态渲染函数 返回node节点数组
    const renderStatus = () => {
      const {
        status,
        distance
      } = state;
      // 根据当前状态, 通过对应插槽  slots[status]渲染
      if (slots[status]) {
        return slots[status]({
          distance
        });
      }
      const nodes = [];
      // [pulling, loosing, succes] 时候添加
      if (TEXT_STATUS.includes(status)) {
        nodes.push(_createVNode("div", {
          "class": bem("text")
        }, [getStatusText()]));
        // 当为loading时添加
      }
      if (status === "loading") {
        nodes.push(_createVNode(Loading, {
          "class": bem("loading")
        }, {
          default: getStatusText
        }));
      }
      return nodes;
    };

    // 展示成功状态后 延迟关闭
    const showSuccessTip = () => {
      state.status = "success";
      // 延迟successDuration后关闭  
      setTimeout(() => {
        setStatus(0);
      }, +props.successDuration);
    };


    const checkPosition = (event) => {
      // 当嵌套父级可以滚动时, 父级滚动到顶点后才可以判断 下拉刷新
      reachTop = getScrollTop(scrollParent.value) === 0;
      if (reachTop) {
        state.duration = 0;
        touch.start(event);
      }
    };

    // 开始滑动
    const onTouchStart = (event) => {
      if (isTouchable()) {
        checkPosition(event);
      }
    };
    // 滑动中
    const onTouchMove = (event) => {
      if (isTouchable()) {
        if (!reachTop) {
          // 滑动衔接时, 之前reachTop可能不为0, 要重新checkPosition, 用于计算跟手距离
          checkPosition(event);
        }
        const {
          deltaY
        } = touch;
        touch.move(event);
        // 移动距离> 0  而且方向垂直
        if (reachTop && deltaY.value >= 0 && touch.isVertical()) {
          preventDefault(event);
          // ease设定阻尼感距离, 并且设定状态
          setStatus(ease(deltaY.value));
        }
      }
    };

    // 滑动结束
    // pulling >>> normal
    // loosing >>> loading >>> 外部状态修改 >>> success >>> normal
    const onTouchEnd = () => {
      if (reachTop && touch.deltaY.value && isTouchable()) {
        state.duration = +props.animationDuration;
        // 在loosing状态时,  直接切为loading状态
        if (state.status === "loosing") {
          setStatus(+props.headHeight, true);
          // 触发外部loading状态
          emit("update:modelValue", true);
          // 其它状态直接为normal
          nextTick(() => emit("refresh"));
        } else {
          setStatus(0);
        }
      }
    };

    // 监听组件是否处于加载中状态
    watch(() => props.modelValue, (value) => {
      state.duration = +props.animationDuration;
      if (value) {
        // 外部手动  置为loading状态
        setStatus(+props.headHeight, true);
      } else if (slots.success || props.successText) {
        showSuccessTip();
      } else {
        setStatus(0, false);
      }
    });


    useEventListener("touchmove", onTouchMove, {
      target: track
    });


    return () => {
      var _a;
      // 状态切换时计算  distance,突变css过渡实现动画
      const trackStyle = {
        transitionDuration: `${state.duration}ms`,
        transform: state.distance ? `translate3d(0,${state.distance}px, 0)` : ""
      };

      // 组件结构van-pull-refresh[van-pull-refresh__track[van-pull-refresh__head slot内容]]
      return _createVNode("div", {
        "ref": root,
        "class": bem()
      }, [_createVNode("div", {
        "ref": track,
        "class": bem("track"),
        "style": trackStyle,
        "onTouchstartPassive": onTouchStart,
        "onTouchend": onTouchEnd,
        "onTouchcancel": onTouchEnd
        // head默认  定位到顶部不可见区域 top -本身高度
      }, [_createVNode("div", {
        "class": bem("head"),
        "style": getHeadStyle()
      }, [renderStatus()]), (_a = slots.default) == null ? void 0 : _a.call(slots)])]);
    };
  }
});
export {
  stdin_default as default,
  pullRefreshProps
};
